# -*- encoding: utf8 -*-

from inspect import getargspec
from functools import wraps
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core import mail
from reps.interns.models import *

import random


def teacher_only(fn):
    @wraps(fn)
    def restricted(*args, **kargs):
        teacher = args[0].user.teacher()
        if teacher:
            argspec = getargspec(fn)
            if 'teacher' in argspec[0] or argspec[2]:   # argument injection
                return fn(teacher=teacher, *args, **kargs)
            else:
                return fn(*args, **kargs)
        else:
            return HttpResponseRedirect('/forbidden/')
    return restricted


def teacher_or_dean_only(fn):
    @wraps(fn)
    def restricted(*args, **kargs):
        teacher = args[0].user.teacher()
        dean = args[0].user.dean()
        if teacher:
            argspec = getargspec(fn)
            if 'teacher' in argspec[0] or argspec[2]:   # argument injection
                return fn(teacher=teacher, *args, **kargs)
            else:
                return fn(*args, **kargs)
        elif dean:
            argspec = getargspec(fn)
            if 'dean' in argspec[0] or argspec[2]:   # argument injection
                return fn(dean=dean, *args, **kargs)
            else:
                return fn(*args, **kargs)
        else:
            return HttpResponseRedirect('/forbidden/')
    return restricted


def verify_existence(model, arg_name, allow_none=False):
    def decorate(fn):
        @wraps(fn)
        def verifier(*args, **kargs):
            arguments, args_name, kargs_name, defaults = getargspec(fn)
            try:
                arg_val = args[arguments.index(arg_name)]
            except:
                arg_val = kargs.get(arg_name, None)
            if arg_val is None:
                return fn(*args, **kargs)
            else:
                id = int(arg_val)
            try:
                model.objects.get(id=id)
                return fn(*args, **kargs)
            except:
                return render('simple_message.html', args[0], {'topic': 'Błąd'})
        return verifier
    return decorate


def render_template(request, template='home.html'):
    return render(template, request)


def render(template, request, data={}):
    specializations = []
    user = request.user
    if user.is_authenticated():
        try:
            profile = user.get_profile()
            specializations = profile.get_specializations()
            if user.student() and 'selected_specialization' not in request.session:
                request.session['selected_specialization'] = specializations[0]
        except:
            pass
    data.update({'available_specializations': specializations,
                 'selected_specialization':\
                    request.session.get('selected_specialization', ''),
                 'return_url': return_url(request)})
    current_msg = data.get('msg', None)
    if not current_msg and 'msg' in request.GET:
        data['msg'] = request.GET['msg']
    return render_to_response(template, data, RequestContext(request))


def returnable(fn):
    @wraps(fn)
    def decorated(request, *args, **kargs):
        #path = request.path.split(?)[0]
        path = request.META['PATH_INFO']
        request.session['return_to'] = path
        return fn(request, *args, **kargs)
    return decorated


def return_url(request, msg=None):
    url = request.session.get('return_to', '/')
    if msg:
        return url + u'?msg=%s' % msg
    else:
        return url


def send_mail(subject, message, to):
    user = Setting.email_user()
    if user:
        mail.send_mail(subject, message, from_email=Setting.email_address(),
                       recipient_list=[to], auth_user=user,
                       auth_password=Setting.email_password())
    else:
        mail.send_mail(subject, message, from_email=Setting.email_address(),
                       recipient_list=[to])


def generate_password():
    return ''.join(random.sample('23456789qwertyupasdfghjkzxcvbnm', 8))

